package com.example.wenmini.service.humanlike;

import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.springframework.stereotype.Component;

import java.util.Random;
import java.util.UUID;

@Component
public class FingerprintGenerator {
    private static final Random random = new Random();
    private static final String[] LANGUAGES = {"zh-CN", "zh", "en-US"};
    private static final String[] PLATFORMS = {"Win32", "MacIntel", "Linux_x86_64"};
    
    public String generateRandomUA() {
        int major = random.nextInt(90, 121);
        int build = random.nextInt(1000, 9999);
        return String.format(
            "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 " +
            "(KHTML, like Gecko) Chrome/%d.0.%d.%d Safari/537.36",
            major, build/1000, build%1000
        );
    }
    
    public String generateUserAgent() {
        return generateRandomUA();
    }
    
    public String generatePlatform() {
        return PLATFORMS[random.nextInt(PLATFORMS.length)];
    }
    
    public void injectDynamicFingerprint(WebDriver driver) {
        String canvasFingerprint = generateCanvasFingerprint();
        String webglFingerprint = generateWebGLFingerprint();
        
        ((JavascriptExecutor)driver).executeScript(
            "Object.defineProperty(navigator, 'plugins', {value: [" +
            "  {name: 'Chrome PDF Plugin', filename: 'internal-pdf-viewer'}," +
            "  {name: 'Chrome PDF Viewer', filename: 'mhjfbmdgcfjbbpaeojofohoefgiehjai'}" +
            "], configurable: false});" +
            
            "Object.defineProperty(navigator, 'languages', {get: () => " + generateLanguages() + "});" +
            
            "Object.defineProperty(navigator, 'platform', {get: () => '" + 
            PLATFORMS[random.nextInt(PLATFORMS.length)] + "'});" +
            
            "Object.defineProperty(navigator, 'hardwareConcurrency', {value: " + 
            (2 + random.nextInt(6)) + "});" +
            
            "Object.defineProperty(navigator, 'deviceMemory', {value: " + 
            (1 << random.nextInt(3)) + "});" +
            
            // Canvas指纹
            "HTMLCanvasElement.prototype.getContext = function(orig) {" +
            "  return function(type) {" +
            "    const ctx = orig.apply(this, arguments);" +
            "    if(type === '2d') {" +
            "      const oldGetImageData = ctx.getImageData;" +
            "      ctx.getImageData = function() {" +
            "        const imageData = oldGetImageData.apply(this, arguments);" +
            "        imageData.data[0] = " + random.nextInt(256) + ";" +
            "        return imageData;" +
            "      };" +
            "    }" +
            "    return ctx;" +
            "  };" +
            "}(HTMLCanvasElement.prototype.getContext);" +
            
            // WebGL指纹
            "const origGetParameter = WebGLRenderingContext.prototype.getParameter;" +
            "WebGLRenderingContext.prototype.getParameter = function(parameter) {" +
            "  if(parameter === 37445) {" +
            "    return '" + webglFingerprint + "';" +
            "  }" +
            "  return origGetParameter.apply(this, arguments);" +
            "};"
        );
    }
    
    private String generateCanvasFingerprint() {
        return UUID.randomUUID().toString().replace("-", "").substring(0, 16);
    }
    
    private String generateWebGLFingerprint() {
        return String.format("%08x", random.nextInt()).toUpperCase();
    }
    
    private String generateLanguages() {
        StringBuilder sb = new StringBuilder("[");
        int count = 1 + random.nextInt(2);
        for (int i = 0; i < count; i++) {
            if (i > 0) sb.append(",");
            sb.append("'").append(LANGUAGES[random.nextInt(LANGUAGES.length)]).append("'");
        }
        return sb.append("]").toString();
    }
}
